import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  Dimensions,
  AsyncStorage,
  TouchableOpacity,
  Alert,
  Image
} from 'react-native';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import styles from './indexStyle';
import ProgressBar from '../global/ProgressBar';
import EditSendOrder from './editSendOrder';
import EditBuyOrder from './editBuyOrder';
import EditExpressOrder from './editExpressOrder';
import EditLockkeyOrder from './editLockkeyOrder';
import EditOtherOrder from './editOtherOrder';
import EditNursingOrder from './editNursingOrder';
import SimpleDialog from '../global/SimpleViewDialog';
import Toast from 'react-native-sk-toast';
import api from '../../services/api';

import DeviceStorage from '../global/DeviceStorage';
import ScrollableTabBar from '../global/scrollableTabView/ScrollableTabBar';

var windowWidth = Dimensions.get('window').width;
var windowHeight = Dimensions.get('window').height;
class AddOrder extends Component {
    constructor(props) {
		super(props);

		this.state = {
			isLoading: true,
			isRefreshing: false,
			tab: 0,
            showPayOrderDialog:false,
            showTimes:0,
            orderDetail:null
		};

        this.serviceTypeMap = [
            'send',
            'buy',
            'express',
            'lockkey',
            'other',
            'nursing'
        ];

        this.serviceTypeKV = [
            'send':'代送',
            'buy':'代买',
            'express':'快递',
            'lockkey':'钥匙保管',
            'other':'其他服务',
            'nursing':'护理服务',
        ]

		// this._getTabHeight = this._getTabHeight.bind(this);
		this._onChangeTab = this._onChangeTab.bind(this);
		this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentWillMount() {
		// this._retrieveDetails();

	}

    componentWillUnmount(){
    }

    _clearDataAction(){
        let {session} = this.props;
        Alert.alert(
          '提示',
          '确定清除当前页面内容吗？',
          [
            {text: '取消', onPress: () => {}, style: 'cancel'},
            {text: '确定', onPress: () => {

                if (session && session.user && session.user.productKey == "HuLiZhan") {
                    let type = 'nursing';
                    DeviceStorage.delete("@order@"+type);
                    this.refs['order_'+type] && this.refs['order_'+type].wrappedInstance.clearContent();
                }else{
                    let tab = this.state.tab,
                        type = this.serviceTypeMap[tab];

                    DeviceStorage.delete("@order@"+type);
                    this.refs['order_'+type] && this.refs['order_'+type].wrappedInstance.clearContent();
                }


            }},
          ],
          { cancelable: false }
       );
    }

    _onNavigatorEvent(event) {

        if (event.type === 'NavBarButtonPress') {
			if (event.id === 'clear') {
                this._clearDataAction();
			}
		}

	}

    _onChangeTab({ i, ref }) {
        // let page = this.props.page || 0;
		this.setState({ tab: i });
	}

    _checkDetailOrder(){

        let {orderArrearageInfo} = this.state;
        let {navigator} = this.props;
        console.log('test-_checkDetailOrder',navigator);
        // dispatch(actions.order.order_get_cardobj(cardObj));
        navigator.push({
            title: "订单详情",
            backButtonTitle:'',
            screen: 'housekeeperapp.orderdetail',
            passProps: {
                orderId:orderArrearageInfo.id
            },
            navigatorStyle:{
                tabBarHidden: true,
                navBarTextColor: 'white',
                navBarButtonColor: 'white',
                navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            // backButtonHidden: true,
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ],
                rightButtons: [
                    {
                        id: 'reload',
                        testID: 'order_reload',
                        title: '刷新'
                    }
                ]
            }
        });

    }
    _closePayOrderDialog(){
        this.setState({
            showPayOrderDialog:false,
        })
    }

    async _notifyOwnerPayOrder(){
        let {notifyPhone} = this.state;
        let {session} = this.props;
        let result = await api.post('/order/sendNonPayOrderLink',{phone:notifyPhone})
        console.log('test--_notifyOwnerPayOrder',result);
        if (result.cd !=0) {
            Toast.bottom(result.msg);
            return;
        }
        Toast.bottom("已提醒"+(session && session.user && session.user.productKey == "HuLiZhan" ? "用户":"业主"+"支付"))
        this.setState({
            showPayOrderDialog:false,
        })
    }

    _onShowDialog(phone,orderArrearageInfo,orderCount){
        console.log('test',phone);
        let {showTimes} = this.state;
        showTimes = showTimes + 1;
        console.log('test,showTimes=',showTimes);
        console.log('test,orderArrearageInfo=',orderArrearageInfo);
        this.setState({
            showPayOrderDialog:true,
            notifyPhone:phone,
            showTimes,
            orderArrearageInfo,
            orderCount,
        })
    }

    chooseType = (type) => {
        switch (type) {
            case "send":
                return  "代送"
            case "buy":
                return  "代买"
            case "express":
                return "快递"
            case "lockkey":
                return "钥匙保管"
            case "other":
                return "其他服务"
            case "nursing":
                return "护理服务"
            default:
               return  "其他服务"
        }
    }

    _renderPwdDialog() {
        let {showPayOrderDialog,orderArrearageInfo,orderCount} = this.state
        let {session} = this.props;
        let s = "";
        if (session && session.user && session.user.productKey == "HuLiZhan") {
            s = "用户"
        }else{
            s = "业主"
        }
        return (
            <SimpleDialog
                offset={-100}
                open={showPayOrderDialog}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin:10,overflow:'hidden',backgroundColor:'#FFFFFF'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={{paddingTop: 24,justifyContent:  'center', alignItems:'center' }}>
                        <Image source={require('../../../img/order_arrearage_icon.png')}  />


                        <View style={styles.arrearageDialogTopContainer}>
                            <Text style={{textAlign:'center',color:'#565656',fontSize:15}}>该{s}存在</Text>
                            <Text style={{textAlign:'center',color:'#EA5404',fontSize:15}}>{orderCount}</Text>
                            <Text style={{textAlign:'center',color:'#565656',fontSize:15}}>个未支付订单</Text>
                        </View>
                        <Text style={{textAlign:'center',marginBottom:20,marginLeft: 15,marginRight:15,fontSize:15,color:'#565656'}}>需要{s}支付后才可以新增订单</Text>
                        
                        <View style={{flexDirection:'row'}}>
                            <View style={[styles.arrearageDialogInfo,{justifyContent:'center',alignItems:'center'}]}>
                                <Text style={styles.arrearageDialogType,{fontSize:13}}> 
                                    最近一笔未支付订单：{orderArrearageInfo && orderArrearageInfo.serviceType ? this.chooseType(orderArrearageInfo.serviceType) : ``}订单
                                </Text>
                                <Text style={styles.arrearageDialogTime,{fontSize:13}}> 订单时间：{orderArrearageInfo && orderArrearageInfo.serviceTime ? orderArrearageInfo.serviceTime:''}</Text>
                                <View style={styles.arrearageDialogMoneyContainer}>
                                    <Text style={{color:'#565656',fontSize:13}}>
                                        欠费金额：
                                    </Text>
                                    <Text style={{color:'#EA5404',fontSize:13,fontWeight:'bold'}}>
                                        ¥{orderArrearageInfo && orderArrearageInfo.payMoney ? orderArrearageInfo.payMoney.toFixed(2):'0'}
                                    </Text>
                                </View>
                                
                                <TouchableOpacity style={styles.arrearageDialogDetailContainer} onPress={this._checkDetailOrder.bind(this)}>
                                    <Text style={styles.arrearageDialogDetail,{fontSize:13}}> 查看订单详情</Text>
                                </TouchableOpacity>
                                
                            </View>
                        </View>

                        
                        
                        <View style={styles.arrearageDialogButtonContainer}>
                            <TouchableOpacity style={styles.arrearageDialogButton} onPress={this._closePayOrderDialog.bind(this)}>
                                <Text style={styles.arrearageDialogClose}>关闭</Text>
                            </TouchableOpacity>
                            <View style={styles.arrearageDialogDivideLine}></View>
                            <TouchableOpacity style={styles.arrearageDialogButton} onPress={this._notifyOwnerPayOrder.bind(this)}>
                                <Text style={styles.arrearageDialogSendMsg}>提醒{s}支付</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }

    render() {
        let page = this.props.page || 0;
        let sourceMap = ['create','create','create','create','create','create'];
        sourceMap[page] = this.props.source;
        let {session} = this.props;

        if (session && session.user && session.user.productKey == "HuLiZhan") {
            return(
                    <View style={{flex:1}}>
                        <EditNursingOrder
                            tabLabel="护理服务"
                            data={this.props.data}
                            source={sourceMap[5]}
                            userPhone={this.props.userPhone}
                            type={'nursing'}
                            ref='order_nursing'
                            navigator={this.props.navigator}/>
                    </View>
                )
        }

        return (
            <View style={{flex:1}}>
                <ScrollableTabView
                    style={{marginTop:-7,}}
                    onChangeTab={this._onChangeTab}
                    initialPage={page}
                    locked={this.props.source=='edit'?true:false}
                    renderTabBar={() => (
                        <ScrollableTabBar
                            ref={component => this.tabBar = component}
                            activeTextColor={"#EA5404"}
                            inactiveTextColor={"#555555"}
                            textStyle={styles.textStyle}
                            mark={true}
                            markStyle={styles.markStyle}
                            markTextStyle={styles.markTextStyle}
                            underlineStyle={styles.underlineStyle}
                            style={[styles.tabBar,this.props.source=='edit'?{height:0}:{}]}
                        />
                    )}>
                    <EditSendOrder
                        tabLabel="代送"
                        data={this.props.data}
                        source={sourceMap[0]}
                        userPhone={this.props.userPhone}
                        type={'send'}
                        ref='order_send'
                        navigator={this.props.navigator}
                        onShowPayNotifyDialog={this._onShowDialog.bind(this)}
                        showTimes={this.state.showTimes}
                        />
                    <EditBuyOrder
                        tabLabel="代买"
                        data={this.props.data}
                        source={sourceMap[1]}
                        userPhone={this.props.userPhone}
                        ref='order_buy'
                        type={'buy'}
                        navigator={this.props.navigator}
                        onShowPayNotifyDialog={this._onShowDialog.bind(this)}
                        showTimes={this.state.showTimes}
                        />
                    <EditExpressOrder
                        tabLabel="快递"
                        data={this.props.data}
                        source={sourceMap[2]}
                        userPhone={this.props.userPhone}
                        ref='order_express'
                        type={'express'}
                        navigator={this.props.navigator}
                        onShowPayNotifyDialog={this._onShowDialog.bind(this)}
                        showTimes={this.state.showTimes}
                        />
                    <EditLockkeyOrder
                        tabLabel="保管钥匙"
                        data={this.props.data}
                        source={sourceMap[3]}
                        userPhone={this.props.userPhone}
                        ref='order_lockkey'
                        type={'lockkey'}
                        navigator={this.props.navigator}
                        onShowPayNotifyDialog={this._onShowDialog.bind(this)}
                        showTimes={this.state.showTimes}
                        />
                    <EditOtherOrder
                        tabLabel="其他服务"
                        data={this.props.data}
                        source={sourceMap[4]}
                        userPhone={this.props.userPhone}
                        type={'other'}
                        ref='order_other'
                        navigator={this.props.navigator}
                        onShowPayNotifyDialog={this._onShowDialog.bind(this)}
                        showTimes={this.state.showTimes}
                        />
                
                </ScrollableTabView>
                {this._renderPwdDialog()}
            </View>

        );
    }
}

var connectHelper = require('../../services/connectHelper');
AddOrder = connectHelper(state => state)(AddOrder);

module.exports = AddOrder;
